package com.dk.smsexpress.server.imp;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;

import com.dk.smsexpress.common.base.IMobiSmsAutoSelectAccount;
import com.dk.smsexpress.common.base.MobiAccount;
import com.dk.smsexpress.common.exception.ExceptionConstant;
import com.dk.smsexpress.common.exception.SmsException;
import com.dk.smsexpress.server.utils.Formatter;
import com.dk.smsexpress.server.utils.XMLUtils;

public class MobiSmsAutoSelectAccount implements IMobiSmsAutoSelectAccount {

	final static Logger logger = LoggerFactory
			.getLogger(MobiSmsManualSelectAccount.class);

	private MobiSms mobiSms = null;
	private List<MobiAccount> mobiAccounts = new ArrayList<MobiAccount>();
	private MobiAccount activeAccount;

	public MobiSmsAutoSelectAccount() {
		loadAccountList();
		getActiveAccount();
		logger.info("Initiate instance");
	}

	private void loadAccountList() {
		try {
			List<Map<String, String>> accountHasmap = XMLUtils
					.parseXML(
							"d:/Study/EclipseWorkspaceJee/SmsServer/WebContent/resource/account.xml",
							"account", "username", "password");
			for (Map<String, String> account : accountHasmap) {
				MobiAccount mobiAccount = new MobiAccount(
						account.get("username"), account.get("password"));
				mobiAccounts.add(mobiAccount);
			}
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error(e.getMessage());
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error(e.getMessage());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error(e.getMessage());
		}
	}

	private void getActiveAccount() {
		for (MobiAccount mobiAccount : mobiAccounts) {
			if (mobiAccount.getMessageLeft() > 0) {
				activeAccount = mobiAccount;
				return;
			}
		}
	}

	@Override
	public void SendMobiSMS(String phoneNum, String message)
			throws SmsException, IOException {

		if (mobiSms == null) {
			mobiSms = new MobiSms(activeAccount);
		}

		if (activeAccount.getMessageLeft() <= 0) {
			getActiveAccount();
			mobiSms = new MobiSms(activeAccount);
		}
		if (!Formatter.isValidPhoneNumber(phoneNum)) {
			throw new SmsException(ExceptionConstant.INVALID_PHONE_NUMBER);
		}
		phoneNum = Formatter.parsePhoneNumber(phoneNum);

		mobiSms.setPhoneNum(phoneNum);
		mobiSms.setMessage(message);
		if (mobiSms.getMessageLeft() > 0) {
			mobiSms.sendMessage();
		} else {
			throw new SmsException(ExceptionConstant.OUT_OFF_MESSAGE);
		}
	}
}
